package mynet;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @Auther: cty
 * @Date: 2020/1/13 16:38
 * @Description:
 * @version: 1.0
 */
public class Be_UdpTalkReceive implements Runnable{
    private DatagramSocket receiver;
    private String from;

    Be_UdpTalkReceive(String from, int port){
        this.from = from;
        //1 创建接收端
        try {
            receiver = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            //2 准备容器，封装成DatagramPacket包裹
            byte[] container = new byte[1024*64];  //最大一次接收64kB的数据包
            DatagramPacket packet = new DatagramPacket(container,0,container.length);
            try {
                //3 接收数据和处理数据
                receiver.receive(packet);
                byte[] datas = packet.getData();
                int len = packet.getLength();
                String data = new String(datas,0,len);
                System.out.println(from+": "+data);
                if(data.equals("bye")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //4 释放资源
        receiver.close();
    }

    public static void main(String[] args) {

    }
}
